﻿using System.Windows;
/*
 * Utilisateur: Masy Freddy
 * Date: 31/10/2011
 * Heure: 6:24
 */
namespace ProviderCinePassion
{
	using System;
	using System.Collections.Generic;
	using System.Xml.Serialization;
	using System.Linq;
	using MetaVideoEditorEvolved.AddIn.AddInViews;
	using MetaVideoEditorEvolved.AddIn.Entity;
	using MetaVideoEditorEvolved.Helper;
	using System.Globalization;

	[System.AddIn.AddIn("CinePassion",
	                    Version = "1.0.0.0",
	                    Description = "Fournisseur d'accès de CinePassion",
	                    Publisher = "Masy Freddy")]
	public class CinePassion : ProviderView
	{
		private readonly string xbmcKey = "2952351097998ac1240cb2ab7333a3d2";
		private string search = @"http://passion-xbmc.org/scraper/API/1/Movie.Search/{0}/{1}/Title/fr/XML/{2}/{3}",
		getInfo = @"http://passion-xbmc.org/scraper/API/1/Movie.GetInfo/{0}/{1}/ID/fr/XML/{2}/{3}",
		mediaLink = @"http://passion-xbmc.org/scraper/index2.php?Page=ViewMovie&ID=";
		private ConfigurationAddIn configurationAddIn;
		
		public CinePassion()
		{
			configurationAddIn = ConfigurationManager.Deserialize();
			
			if(configurationAddIn == null)
			{
				configurationAddIn = new ConfigurationAddIn()
				{
					TraceLevel = "Error",
					UserName = string.Empty,
					Password = string.Empty
				};
				
				ConfigurationManager.Serialize(configurationAddIn);
			}
			
			Tracer.TracerInstance.Level= string.IsNullOrEmpty(configurationAddIn.TraceLevel) ? TracerLevel.Error : (TracerLevel)Enum.Parse(typeof(TracerLevel), configurationAddIn.TraceLevel);
			Tracer.TracerInstance.FileName = "CinePassion";
		}
		
		public override List<MetaVideoEditorEvolved.AddIn.Entity.ProviderSearchResult> FindPossible(MetaVideoEditorEvolved.AddIn.Entity.ProviderSearchRequest request)
		{
			try
			{
				Tracer.TracerInstance.TraceInformation(string.Format("Start the CinePassion FindPossible (SearchName:{0}-Type{1})", request.Name, request.Type.ToString()));
				List<ProviderSearchResult> providerResults = new List<ProviderSearchResult>();
				
				if(!string.IsNullOrEmpty(configurationAddIn.UserName) &&
				   !string.IsNullOrEmpty(configurationAddIn.Password) &&
				   request.Type == MediaType.Movie)
				{
					var resultMovieWebRequest = DownloadManager.RetrieveXmlWebRequest(string.Format(search, configurationAddIn.UserName, configurationAddIn.Password,xbmcKey, DownloadManager.UrlEncode(request.Name)));
					
					if(resultMovieWebRequest != null)
					{
						if(resultMovieWebRequest.Root.Name == "errors")
						{
							Tracer.TracerInstance.TraceInformation("Error in provider cinepassion : " + resultMovieWebRequest.Root.Value);
							
							if(resultMovieWebRequest.Root.Value.ToLower() != "no results")
							{
								MessageBox.Show(resultMovieWebRequest.Root.Value, "Error : Provider CinePassion", MessageBoxButton.OK, MessageBoxImage.Warning);
							}
							
							return providerResults;
						}
						
						Tracer.TracerInstance.TraceInformation("Start to Deserialize");
						results searchMovie = new XmlSerializer(typeof(results)).Deserialize(resultMovieWebRequest.Root.CreateReader()) as results;
						Tracer.TracerInstance.TraceInformation("End Deserialize");
						
						if(searchMovie != null &&
						   searchMovie.movie != null)
						{
							foreach (var element in searchMovie.movie) {
								var posters = from p in element.images
									where p.type.ToLower() == "poster" &&
									p.size.ToLower() == "thumb"
									select p.url;
								
								providerResults.Add(new ProviderSearchResult
								                    {
								                    	Id = !string.IsNullOrEmpty(element.id) ? int.Parse(element.id) : 0,
								                    	MediaUrl = !string.IsNullOrEmpty(element.id) ? new Uri(mediaLink + element.id) : null,
								                    	Name = element.title,
								                    	OriginalName = element.originaltitle,
								                    	Overview = element.plot,
								                    	Picture = (posters != null && posters.Any()) ? new Uri(posters.First()) : null,
								                    	Year = string.IsNullOrEmpty(element.year) ? 0 : int.Parse(element.year)
								                    });
							}
						}
					}
				}
				
				return providerResults;
			}
			catch(Exception ex)
			{
				Tracer.TracerInstance.TraceError("Exception in CinePassion provider FindPossible (SearchName:{0}-Type{1})", ex);
				throw new InvalidPluginException(Properties.Resources.UnknownError, ex);
			}
		}
		
		public override MetaVideoEditorEvolved.AddIn.Entity.Movie FetchMovie(int movieId)
		{
			try
			{
				Tracer.TracerInstance.TraceInformation(string.Format("Start the CinePassion FetchMovie (MovieId:{0})", movieId));
				MetaVideoEditorEvolved.AddIn.Entity.Movie result = null;
				
				if(!string.IsNullOrEmpty(configurationAddIn.UserName) &&
				   !string.IsNullOrEmpty(configurationAddIn.Password))
				{
					var resultMovieWebRequest = DownloadManager.RetrieveXmlWebRequest(string.Format(getInfo, configurationAddIn.UserName, configurationAddIn.Password,xbmcKey,  movieId));
					
					if(resultMovieWebRequest != null)
					{
						Tracer.TracerInstance.TraceInformation("Start to Deserialize");
						movie searchMovie = new XmlSerializer(typeof(movie)).Deserialize(resultMovieWebRequest.Root.CreateReader()) as movie;
						Tracer.TracerInstance.TraceInformation("End Deserialize");
						
						if(searchMovie != null)
						{
							result = new Movie()
							{
								Countries = new List<string>(),
								Genres = new List<string>(),
								CastMembers = new List<CastMember>(),
								Backdrops = new List<Uri>(),
								Posters = new List<Uri>(),
								Trailers = new List<Trailer>(),
								Studios = new List<string>()
							};
							
							result.Duration = string.IsNullOrEmpty(searchMovie.runtime) ? 0 : int.Parse(searchMovie.runtime);
							result.Id = string.IsNullOrEmpty(searchMovie.id) ? 0 : int.Parse(searchMovie.id);
							result.MPAARating = (searchMovie.certifications != null && searchMovie.certifications.Any()) ? searchMovie.certifications.First().Value : string.Empty;
							result.OriginalTitle = searchMovie.originaltitle;
							result.Overview = searchMovie.plot;
							result.SortTitle = searchMovie.sorttitle;
							result.Title = searchMovie.title;
							result.Year = string.IsNullOrEmpty(searchMovie.year) ? 0 : int.Parse(searchMovie.year);
							result.Rating = (searchMovie.ratings != null && searchMovie.ratings.Any()) ?float.Parse(searchMovie.ratings.First().Value, CultureInfo.InvariantCulture) : 0.0F;
							
							if(searchMovie.countries != null)
							{
								foreach (var element in searchMovie.countries) {
									result.Countries.Add(element);
								}
							}
							
							if(searchMovie.genres != null)
							{
								foreach (var element in searchMovie.genres) {
									result.Genres.Add(element);
								}
							}
							
							if(searchMovie.studios != null)
							{
								foreach (var element in searchMovie.studios) {
									result.Studios.Add(element);
								}
							}
							
							if(searchMovie.trailers != null)
							{
								foreach (var element in searchMovie.trailers) {
									if(!string.IsNullOrEmpty(element))
									{
										result.Trailers.Add(new Trailer
										                    {
										                    	DefaultPath = new Uri(element)
										                    });
									}
								}
							}
							
							if(searchMovie.images != null)
							{
								foreach (var element in searchMovie.images) {
									if(element.size == "original")
									{
										switch (element.type.ToLower()) {
											case "poster":
												result.Posters.Add(new Uri(element.url));
												break;
											case "fanart":
												result.Backdrops.Add(new Uri(element.url));
												break;
										}
									}
								}
							}
							
							if(searchMovie.directors != null)
							{
								foreach (var element in searchMovie.directors) {
									result.CastMembers.Add(new CastMember
									                       {
									                       	FullName = element,
									                       	Activity = "Director"
									                       });
								}
							}
							
							if(searchMovie.casting != null)
							{
								foreach (var element in searchMovie.casting) {
									result.CastMembers.Add(new CastMember
									                       {
									                       	FullName = element.name,
									                       	Activity = "Actor",
									                       	Role = element.character,
									                       	Picture = string.IsNullOrEmpty(element.thumb) ? null : new Uri(element.thumb)
									                       });
								}
							}
							
							Tracer.TracerInstance.TraceSuccessOperation(string.Format("Start the CinePassion FetchMovie (MovieId:{0})", movieId));

							return result;
						}
					}
				}
				
				return null;
			}
			catch(Exception ex)
			{
				Tracer.TracerInstance.TraceError("Exception in CinePassion provider FindPossible (SearchName:{0}-Type{1})", ex);
				throw new InvalidPluginException(Properties.Resources.UnknownError, ex);
			}
		}
		
		public override MetaVideoEditorEvolved.AddIn.Entity.Episode FetchEpisode(string serieId, int seasonNumber, int episodeNumber)
		{
			return null;
		}
		
		public override MetaVideoEditorEvolved.AddIn.Entity.Season FetchSeason(string serieId, int seasonNumber)
		{
			return null;
		}
		
		public override MetaVideoEditorEvolved.AddIn.Entity.Serie FetchSerie(string serieId)
		{
			return null;
		}
		
		public override bool HasOption()
		{
			return true;
		}
		
		public override void ShowOption()
		{
			new Option(configurationAddIn).ShowDialog();
		}
	}
}